package slice

import (
	"fmt"
	"log"
	"strconv"
)

func Make() {
	slice := make([]int, 0, 10)
	fmt.Printf("%p\n", &slice)
	fmt.Print(slice)
}

func pointer() {
	nums := []int{1, 2, 4, 5, 6}

	copyNums := make([]int, len(nums))
	copy(copyNums, nums)

	slice := nums[1:4]

	fmt.Println(nums)
	fmt.Println(slice)
	fmt.Println("after change nums[3]=1")

	nums[3] = 1 //公用数组

	fmt.Println(nums)
	fmt.Println(slice)

	slice = copyNums[1:4]
	nums[3] = 5
	copyNums[3] = 1
	fmt.Println("after change copyNums[3]=1")

	fmt.Println(nums)
	fmt.Println(slice)
}

func each() {
	slice := make([]string, 10)

	// mock
	for i := 0; i < 10; i++ {
		slice[i] = strconv.Itoa(i)
	}

	//foreach
	for i, v := range slice {
		// v实际只用了一个地址
		go func(n int, m string) {
			fmt.Println(n, m)
		}(i, v)

		// error
		//go func() {
		//	fmt.Println(i, v) // v闭包逃逸到堆
		//}()
	}

}

func resize() {
	x := []int{1, 2, 4}
	y := x[:2]
	log.Println(x, y)
	log.Println(cap(y), len(y))
	log.Printf("%p,%p", x, y)
	y = append(y, 5)
	log.Println(x, y)
	log.Println(cap(y), len(y))
	log.Printf("%p,%p", x, y)
	y = append(y, 6)
	log.Println(x, y)
	log.Println(cap(y), len(y))
	log.Printf("%p,%p", x, y)
}
